﻿using System.Collections.Generic;

namespace Letter.Net.Kcp;

sealed class SafeStack<T>
{
    public SafeStack() : this(512)
    {
    }

    public SafeStack(int maxSize)
    {
        if (maxSize < 10)
            maxSize = 100;
        this.maxSize = maxSize;
    }

    private Stack<T> stack = new Stack<T>();
    private object sync = new object();
    private int maxSize;

    public int Count
    {
        get
        {
            lock (this.sync)
            {
                return this.stack.Count;    
            }
        }
    }

    public bool TryPop(out T item)
    {
        lock (this.sync)
        {
            if (this.stack.Count > 0)
            {
                item = this.stack.Pop();
                return true;
            }

            item = default;
            return false;
        }
    }

    public bool TryPush(T item)
    {
        lock (this.sync)
        {
            if (this.Count >= this.maxSize)
            {
                return false;
            }
        
            this.stack.Push(item);
            return true;
        }
    }

    public void Clear()
    {
        lock (this.sync)
        {
            this.stack.Clear();
        }
    }
}